# -*- coding: utf-8 -*-
import sys, os, json
from PyQt5.QtCore import pyqtSlot, Qt
from PyQt5.QtWidgets import QWidget, QApplication, QTableWidgetItem, QMessageBox, QMenu, QAction
from Ui import Ui_Form
from SMTPDialog import SMTPDialog
from agent import AgentDialog
from log import LogDialog, delete_log
from threads import NewTaskThread
from scheduler import scheduler

BASE_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))


class MyWindow(QWidget):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.initUi()

    def initUi(self):
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.init_table()

        # 在tablewidget部件上开启右键菜单策略
        self.ui.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.tableWidget.customContextMenuRequested.connect(self.custom_menu)

    def custom_menu(self, pos):
        # 创建右键菜单选项
        contextMenu = QMenu(self)
        copy_menu = QAction("复制", self)
        log_menu = QAction("查看日志", self)
        del_menu = QAction("删除日志", self)

        contextMenu.addAction(copy_menu)
        contextMenu.addAction(log_menu)
        contextMenu.addAction(del_menu)

        copy_menu.triggered.connect(self.copy_content)
        log_menu.triggered.connect(self.look_log)
        del_menu.triggered.connect(self.del_log)
        contextMenu.exec_(self.ui.tableWidget.mapToGlobal(pos))

    def copy_content(self):
        """复制选中值"""
        items = self.ui.tableWidget.selectedItems()
        if len(items) > 0:
            """
            使用 QClipboard 类来实现复制功能
            QClipboard 类提供了与系统剪贴板的交互，可以将文本、图像和其他数据存储到剪贴板中，也可以从剪贴板中检索这些数据
            """
            clipboard = QApplication.clipboard()
            clipboard.setText(items[0].text())
        else:
            QMessageBox.warning(self, "错误", "未选中区域")

    def look_log(self):
        """查看日志"""
        items = self.ui.tableWidget.selectedItems()
        if len(items) > 0:
            row_index = items[0].row()
            asin = self.ui.tableWidget.item(row_index, 0).text()
            self.log = LogDialog(asin)
            self.log.show()

    def del_log(self):
        """删除日志"""
        items = self.ui.tableWidget.selectedItems()
        if len(items) > 0:
            row_index = items[0].row()
            asin = self.ui.tableWidget.item(row_index, 0).text()
            delete_log(asin)

    def init_table(self):
        """初始化表格"""
        file_path = os.path.join(BASE_DIR, 'db', 'db.json')
        with open(file_path, 'rt', encoding='utf-8') as f:
            data_dic = json.load(f)
        # 初始化第3列的列宽
        self.ui.tableWidget.setColumnWidth(2, 200)
        for index, items in enumerate(data_dic):
            self.ui.tableWidget.insertRow(index)
            for col, value in enumerate(items):
                cell = QTableWidgetItem(str(value))
                if col in [0, 4, 5, 6, 7]:
                    cell.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

                self.ui.tableWidget.setItem(index, col, cell)

    @pyqtSlot()
    def on_start_clicked(self):
        """开始执行"""
        self.ui.label.setText("执行中")
        scheduler.start(
            widget=self,
            callback=self.update_table_status
        )

    def update_table_status(self, row_index):
        item = QTableWidgetItem("正在执行")
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        self.ui.tableWidget.setItem(row_index, 6, item)

    @pyqtSlot()
    def on_stop_clicked(self):
        """暂停执行"""
        self.ui.label.setText("正在停止 1/100")

    @pyqtSlot()
    def on_add_clicked(self):
        """添加按钮 将商品数据暂时添加到表格"""
        text = self.ui.lineEdit.text().strip()

        if text and "=" in text:
            asin, price = text.split("=")
            all_asin = self.get_table_ASIN()
            if asin not in all_asin:
                item = [asin, "0", "0", price, "0", "0", "待执行", "5"]
                current_row = self.ui.tableWidget.rowCount()
                self.ui.tableWidget.insertRow(current_row)
                for col, value in enumerate(item):
                    cell = QTableWidgetItem(str(value))
                    if col in [0, 4, 5, 6, 7]:
                        cell.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                    self.ui.tableWidget.setItem(current_row, col, cell)

                # 执行子线程 发送数据包
                self.thread = NewTaskThread(current_row, asin)
                self.thread.success_signal.connect(self.event_success_update)
                self.thread.error_signal.connect(self.event_error_update)
                self.thread.start()

            else:
                QMessageBox.warning(self, "重复", "商品的ASIN重复")
        else:
            QMessageBox.warning(self, "错误", "商品的ASIN输入错误!")

    @pyqtSlot()
    def on_again_init_clicked(self):
        """点击重新初始化"""
        choice_rows = self.ui.tableWidget.selectionModel().selectedRows()
        if choice_rows:
            for row_obj in choice_rows:
                # 获取行号
                row_index = row_obj.row()
                # 更新状态
                cell_status = QTableWidgetItem("正在初始化")
                cell_status.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                self.ui.tableWidget.setItem(row_index, 6, cell_status)
                # 初始化
                asin = self.ui.tableWidget.item(row_index, 0).text().strip()
                self.thread2 = NewTaskThread(row_index, asin)
                self.thread2.success_signal.connect(self.event_success_update)
                self.thread2.error_signal.connect(self.event_error_update)
                self.thread2.start()
        else:
            QMessageBox.warning(self, "错误", "请选择初始化的行")

    @pyqtSlot()
    def on_clear_count_clicked(self):
        """点击清零"""
        choice_rows = self.ui.tableWidget.selectionModel().selectedRows()
        if choice_rows:
            for row_obj in choice_rows:
                # 获取行号
                row_index = row_obj.row()
                # 将第4和第5行清零
                for i in range(4, 6):
                    cell_zero = QTableWidgetItem("0")
                    cell_zero.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                    self.ui.tableWidget.setItem(row_index, i, cell_zero)
        else:
            QMessageBox.warning(self, "错误", "请选择要清零的行")

    @pyqtSlot()
    def on_del_item_clicked(self):
        """删除监控项"""
        choice_rows = self.ui.tableWidget.selectionModel().selectedRows()
        if choice_rows:
            # choice_rows.reverse()
            for row_obj in choice_rows:
                # 获取行号
                row_index = row_obj.row()
                self.ui.tableWidget.removeRow(row_index)
        else:
            QMessageBox.warning(self, "错误", "请选择要删除的行")

    @pyqtSlot()
    def on_smtp_set_clicked(self):
        """SMTP报警"""
        self.smtp = SMTPDialog()
        self.smtp.show()

    @pyqtSlot()
    def on_agent_ip_clicked(self):
        """代理IP配置"""
        self.agent = AgentDialog()
        self.agent.show()

    def event_success_update(self, row_index, title, url):
        """数据请求成功,更新表格"""
        cell_title = QTableWidgetItem(title)
        self.ui.tableWidget.setItem(row_index, 1, cell_title)

        cell_url = QTableWidgetItem(url)
        self.ui.tableWidget.setItem(row_index, 2, cell_url)

        cell_status = QTableWidgetItem("初始化完成")
        cell_status.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        self.ui.tableWidget.setItem(row_index, 6, cell_status)

    def event_error_update(self, row_index, title, url):
        """数据请求失败，更新表格"""
        cell_title = QTableWidgetItem(title)
        self.ui.tableWidget.setItem(row_index, 1, cell_title)

        cell_url = QTableWidgetItem(url)
        self.ui.tableWidget.setItem(row_index, 2, cell_url)

        cell_status = QTableWidgetItem("初始化失败")
        cell_status.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        self.ui.tableWidget.setItem(row_index, 6, cell_status)

    def get_table_ASIN(self) -> list:
        """获取表格ASIN列的所有值"""
        column_index = 0
        values = []
        for row in range(self.ui.tableWidget.rowCount()):
            item = self.ui.tableWidget.item(row, column_index)
            if item is not None:
                values.append(item.text())
        return values


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())
